package com.freewater.springboot.demo.ioc.lifecycle;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.Lifecycle;

import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

@Slf4j
public class LifeCycleComponent implements Lifecycle {

    private ExecutorService executorService;

    private boolean running;

    public void init() {
        executorService = Executors.newFixedThreadPool(1);
    }

    @Override
    public void start() {
        log.info("异步任务处理开始");
        this.asyncProcess();
    }

    @Override
    public void stop() {
        destroy();
    }

    @Override
    public boolean isRunning() {
        return running;
    }

    public void destroy() {
        this.running = false;
        if (executorService != null && !executorService.isShutdown()) {
            executorService.shutdown();
            try {
                log.info("waiting 2 seconds before shutdownNow");
                if (!executorService.awaitTermination(2, TimeUnit.SECONDS)) {
                    final List<Runnable> notExecutedTasks = executorService.shutdownNow();
                    printUnExecutedTasks(notExecutedTasks);
                }
            } catch (InterruptedException e) {
                log.error("等待期间，destroy方法被interrupted");
            }
            log.info("executorService terminated");
        }
    }

    /**
     * 执行异步任务
     */
    private void asyncProcess() {
        running = true;
        for (int i = 0; i < 4; i++) {
            executorService.execute(new Task(i));
        }
    }

    private void printUnExecutedTasks(List<Runnable> waitingTasks) {
        for (Runnable waitingTask : waitingTasks) {
            Task task = (Task) waitingTask;
            log.info("还未执行的任务：task {}", task.getNum());
        }
    }

}
